package org.fickler

import org.apache.spark.sql.{SaveMode, SparkSession}
import org.apache.spark.sql.functions.{col, count, desc, when}
import org.apache.spark.{SparkConf, SparkContext}

/**
 * @author Fickler
 * @date 2024/1/7 17:00
 */
object UkOperation {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setMaster("local[*]").setAppName("UK")
    val sc = new SparkContext(conf)

    val spark = SparkSession.builder.appName("UkOperation").getOrCreate()

    val inputPath = "src/main/java/org/datas/dft-road-casualty-statistics-accident-1979-2020.csv"
    val df = spark.read.option("header", "true").csv(inputPath)

    // 根据local_authority_ons_district列进行分组计数
    val accidentRegionFrequency = df.withColumn("region",
      when(col("local_authority_ons_district").startsWith("E"), "East")
        .when(col("local_authority_ons_district").startsWith("W"), "West")
        .when(col("local_authority_ons_district").startsWith("S"), "South")
        .when(col("local_authority_ons_district").startsWith("-1"), "North")
        .otherwise("Unknown"))
      .groupBy("region")
      .agg(count("*").alias("accident_count"))
      .orderBy("region")

    accidentRegionFrequency.show()

    val outputPath = "src/main/java/org/UkResult/UkOperation"
    accidentRegionFrequency
      .coalesce(1)
      .write
      .mode("overwrite")
      .option("header", "true")
      .csv(outputPath)

    val mysqlUrl = "jdbc:mysql://localhost:3306/ukaccident"
    val mysqlProperties = new java.util.Properties()
    mysqlProperties.setProperty("user", "root")
    mysqlProperties.setProperty("password", "011216")
    mysqlProperties.setProperty("driver", "com.mysql.jdbc.Driver")

    accidentRegionFrequency.write
      .mode(SaveMode.Overwrite)
      .jdbc(mysqlUrl, "UkOperation", mysqlProperties)

    spark.stop()
  }

}

/**
bin/spark-submit \
--class org.fickler.UkOperation \
--master local[2] \
./examples/jars/accidentgroup3-1.0-SNAPSHOT.jar \
10
 */